# -*- coding: utf-8 -*-
'''
@author: Johnny
@Created on: 2011-6-3
@version: 2011.6.3
@summary: Definition of ThreadManager class and ThreadProxy class
'''
import Queue
from PyQt4 import QtCore
from executor.runner import Runner


class ThreadProxy(QtCore.QThread):
    '''
    Create ThreadManager object and prepare steps.
    '''
    def __init__(self, host_list, timeout, destination, cases):
        '''
        Constructor.
        Keyword arguments:
        host_list -- host list, e.g. [[localhost,4445,*chrome]]
        timeout -- timeout period
        time_stamp -- timestamps for every thread
        destination -- test site'
        steps - step list with test value
        '''
        QtCore.QThread.__init__(self, parent = None)
        self.host_list = host_list
        self.timeout = timeout
        self.cases = cases
        self.dest = destination
        
    def run(self):
        '''
        Execute when start of ThreadProxy object is called. 
        Create ThreadManager object and prepare test steps.
        '''
        tm = ThreadManager(self.host_list, self.timeout, self.dest)
        for case in self.cases:
            tm.add_job(self.dest, case)
        tm.wait_for_complete()
        
    def __del__(self):
        '''
        Destructor.
        '''
        self.existing = True
        self.wait()


class ThreadManager(object):
    '''
    Create and start threads.
    '''

    def __init__(self, host_list, time_out, dest):
        '''
        Constructor.
        Keyword arguments:
        host_list -- host list, e.g. [[localhost,4445,*chrome]]
        timeout -- timeout period
        dest -- test site'
        time_stamp -- timestamps for every thread
        '''
        self.workQueue = Queue.Queue()
        self.workers = []
        self.timeout = time_out
        self._recruitThreads(host_list, dest)
        
    def _recruitThreads(self, host_list, dest):
        '''
        Create and start threads with work queue.
        Keyword arguments:
        host_list -- host list, e.g. [[localhost,4445,*chrome]]
        dest -- test site'
        time_stamp -- timestamps for every thread
        '''
        for host in host_list:
            worker = Runner(self.workQueue, host, dest)
            self.workers.append(worker)
            
    def wait_for_complete(self):
        '''
        Wait for all threads complete.
        '''
        while len(self.workers):
            worker = self.workers.pop()
            worker.join()
            if worker.isAlive() and not self.workQueue.empty():
                self.workers.append(worker)
        print "All test done!"
                
    def add_job(self, dest, case):
        '''
        Add steps to work queue.
        Keyword arguments:
        dest -- test site'
        steps - step list with test value
        '''
        self.workQueue.put((dest, case))
                